<template>
  <div style="margin-top:44px">
      <div class="order-list-box" v-for="(item,index) in orderList" :key="index">
        <h4>订单号：{{item.order_no}} <font class="red45">{{item.status_text}}</font>
        </h4>
        <div class="order-list" @click="toOrderDetailsPage(item.order_no)">
          <dl v-for="(product,i) in item.products" :key="i"  v-if="i<2"  :class="{'gray': product.order_product_status == 3}">
            <dt><img :src="product.product_cover +'?x-oss-process=image/resize,m_pad,h_400,w_400,color_ffffff/quality,Q_80/format,jpg'">
              <font v-if="product.order_product_status == 3">已退款</font>
            </dt>
            <dd>
              <h2>{{product.designer_name}}</h2>
              <p>{{product.product_name}}</p>
              <p class="gray">尺码 ：{{product.size}}</p>
            </dd>
            <h3>
              <font>x{{product.product_qty}}</font>{{product.currency_logo}}{{product.show_price}}
            </h3>
          </dl>
          <div class="order-settle"><font v-if="item.products.length > 2">查看详情</font> <span class="fr">共{{item.total_qty}}件商品 　 合计：¥{{item.amount_payable}}</span></div>
        </div>

        <div class="orderde-btn" style="background-color:#fff">
          <span v-if="item.order_status == 1 || item.order_status == 21">
            <font class="bgf0" @click="payBtn(item.order_no)">{{item.remainTimeStr}}去支付</font>
            <font @click="cancelOrderBtn(item.order_no)">取消订单</font>
          </span>

          <span v-if="item.order_status == 6 || item.order_status == 5 || item.order_status == -1 || item.order_status == -3">
            <font class="bgf0" @click="againBuyBtn(item.products)">再次购买</font>
          </span>

          <span v-if="item.order_status == 4">
            <font class="bgf0" @click="receivedBtn(item.order_no)">确认收货</font>
          </span>

          <span v-if="item.order_status == 4 || item.order_status == 5 || item.order_status == 6 || item.order_status == 33">
            <font @click="logisticsBtn(item.order_no)">订单跟踪</font>
          </span>
        </div>
      </div>
    <div class="spinnerBox" :hidden="footerHide">
      {{loadMoreText}}
      <div class="spinner" v-if="hasMore">
        <div class="bounce1"></div>
        <div class="bounce2"></div>
        <div class="bounce3"></div>
      </div>
    </div>
    <placeholder :show.sync="isPageEmpty" :message.sync="emptyMsg" :hidBtn="hidBtn" @tryAgain="onTap" :styleTop="44"/>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import placeholder from '@/components/placeholder'
import wxpayfn from '@/utils/paymaneger'
import pullmixin from '@/mixins/PullRefreshLayout'
import common from '@/utils/common'
import { timeQuantum } from '@/utils/index'

export default {
  props: {
    orderType: {
      defualt: -1
    },
    show: {
      defualt: false
    }
  },
  data() {
    return {
      scrollHeight: 0,
      isFirst: true,
      orderList: [],
      noData: false,
      noDataText: '全部',
      productObjArr: [],
      Dtime:0
    }
  },
  watch: {
    show: function(newValue, oldValue) {
      if (newValue && this.isFirst) {
        switch (this.orderType) {
          case -1:
            this.noDataText = '全部'
            break
          case '0':
            this.noDataText = '待付款'
            break
          case 1:
            this.noDataText = '待发货'
            break
          case 2:
            this.noDataText = '待收货'
            break
          case 3:
            this.noDataText = '退款'
            break
          default:
            this.noDataText = ''
        }
        this.onRefresh(true)
        this.isFirst = false
      }
    }
  },
  mixins: [pullmixin],
  computed: {
    ...mapState('cart', ['settleData'])
  },
  methods: {
    ...mapActions('cart', ['checkSettle']),
    toOrderDetailsPage(orderNo){
      this.$wx.jumper('/pages/orderDetails/main?orderNo='+ orderNo)
    },
    //去支付
    payBtn(orderNo) {
      wxpayfn.pay(orderNo, data => {
        if (data) {
          this.$wx.showShortToast('支付成功')
          this.$root.$eventHub.$emit('requestPayBack', '')
          this.onRefresh(true)
        } else {
          this.$wx.showShortToast('支付失败')
          this.$root.$eventHub.$emit('requestPayBack', '')
          this.onRefresh(true)
        }
      })
    },
    //取消订单
    cancelOrderBtn(orderNo) {
      const self = this
      wx.showModal({
        title: '提示',
        content: '确认取消订单吗?',
        success(res) {
          self.cancelOrder(res, orderNo)
        }
      })
    },
    async cancelOrder(res, orderNo) {
      if (res.confirm) {
        const data = await this.$fly.post(this.$url.URL_CANCEORDER, {
          order_no: orderNo
        })
        if (data.successCode === 1) {
          this.onRefresh(true)
        }
      }
    },
    //再次购买
    againBuyBtn(products) {
      this.productObjArr = []
      products.forEach(item => {
        let productItem = {
          product_id: item.product_id.toString(),
          product_sku_id: item.product_sku_id.toString(),
          product_qty: item.product_qty.toString()
        }
        this.productObjArr.push(productItem)
      })
      this.againBuy()
    },
    async againBuy() {
      const data = await this.$fly.post(this.$url.URL_ADDBATCH, {
        product_sku_ids: this.productObjArr
      })
      if (data.successCode) {
        await this.checkSettle({
          isSettlePage: false,
          checkedProduct: this.productObjArr
        })
        if (this.settleData) {
          this.$wx.jumper('/pages/cashier/main')
        } else {
          this.$wx.showShortToast(this.errorMsg)
        }
      }
    },
    //订单跟踪
    logisticsBtn(orderNo){
      this.$wx.jumper('/pages/logistics/main?orderNo=' + orderNo)
    },
    //确定收货
    async receivedBtn(orderNo) {
      const data = await this.$fly.post(this.$url.URL_RECEIVEORDER, {
        order_no: orderNo
      })
      if (data.successCode) {
        this.onRefresh(true)
      }
    },
    async onRefresh(isRefresh) {
      if(!this.show){
        this.handlerNotCurrentPage()
        return
      }
      const data = await this.$fly.post(this.$url.URL_ORDERLISTS, {
        page_index: isRefresh
          ? (this.paramsDatas.pageIndex = 1)
          : this.paramsDatas.pageIndex,
        page_size: this.paramsDatas.pageSize,
        order_type: this.orderType
      })
      if (data.successCode) {
        this.Dtime = timeQuantum(data.timestamp)
        this.preHandler(isRefresh, data.data.orders.length)
        if (isRefresh) {
          this.orderList = data.data.orders
          if (data.data.orders.length <= 0) {
            this.noData = true
            this.isPageEmpty = true
            this.hidBtn = true
            this.emptyMsg = `您暂时还没有(${this.noDataText})订单`
          } else {
            this.isPageEmpty = false
            this.noData = false
          }
        } else {
          this.orderList.push.apply(this.orderList, data.data.orders)
        }
      } else {
        this.handlerFail(isRefresh)
      }
    },
    onTap(){
      this.onRefresh(true)
    },
    countdown() {
      let self = this
      var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/
      let timer = setInterval(function() {
        for (let i = 0; i < self.orderList.length; i++) {
          let nowTime = new Date()
          let t = self.orderList[i].expire_time - (nowTime.getTime() + self.Dtime)
          if (t > 0) {
            let day = Math.floor(t / 86400000)
            let hour = Math.floor(t / 3600000)
            let min = Math.floor((t / 60000) % 60)
            let sec = Math.floor((t / 1000) % 60)
            day = day < 10 ? '0' + day : day
            hour = hour < 10 ? '0' + hour : hour
            min = min < 10 ? '0' + min : min
            sec = sec < 10 ? '0' + sec : sec
            let format = ''
            format = `${min}:${sec}`
            // self.orderList[i].remainTimeStr = format
            if (self.orderList[i].order_status == 1) {
              self.$set(self.orderList[i], 'remainTimeStr', format)
            }
          } else {
            // 进行判断 如果数据内所有的倒计时已经结束，那么结束定时器， 如果没有那么继续执行定时器
            let flag = self.orderList.every(
              (val, ind) => !reg.test(val.expire_time - (nowTime.getTime() + self.Dtime))
            )

            if (flag) clearInterval(timer)
            if(self.orderList[i].order_status == 1){
              self.orderList[i].remainTimeStr = `` // 结束文案
              self.orderList[i].order_status = -3
              self.orderList[i].status_text = '已取消'
            }
          }
        }
      }, 1000)
    },
    toIndexPage(){
      wx.switchTab({
        url: '/pages/index/main'
      })
    }
  },
  mounted() {
    console.log('mounted')
    if (this.show && this.isFirst) {
      this.onRefresh(true)
      this.isFirst = false
    }
    this.$root.$eventHub.$on('requestPayBack',(target) => {
      this.onRefresh(true)
      this.countdown()
    });
  },
  created() {
    this.countdown()
    this.scrollHeight = common.getWindowHeight() - 50
  },
  components: {
    placeholder
  }
}
</script>

<style>

</style>
